package org.mx.service.server.websocket;

import org.eclipse.jetty.websocket.api.Session;
import org.mx.spring.utils.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 描述： 一个用于测试Websocket的ECHO
 *
 * @author john peng Date time 2018/10/28 9:34 PM
 */
public class EchoWebsoket extends WsLifeCircleMonitor {
	private static final Logger logger = LoggerFactory.getLogger(EchoWebsoket.class);

	private WsSessionManager manager;

	/**
	 * 默认的构造函数
	 */
	public EchoWebsoket() {
		super("/echo");
		manager = SpringContextHolder.getBean(WsSessionManager.class);
	}

	@Override
	public void hasText(WsConnectKey connectKey, String text) {
		super.hasText(connectKey, text);
		try {
			if (manager != null) {
				Session session = manager.getSession(connectKey);
				if (session != null) {
					session.getRemote().sendString(String.format("Server echo: %s.", text));
				}
			}
		} catch (IOException ex) {
			if (logger.isErrorEnabled()) {
				logger.error("Send any text fail.", ex);
			}
		}
	}
}
